package com.example.fx.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.fx.R
import com.example.fx.databinding.ActivityLoginBinding
import com.example.fx.db.AppDbUtils
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<LoginViewModel,ActivityLoginBinding>() {
    override fun getLayout(): Int  = R.layout.activity_login

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java

    override fun initView() {
        binding.login.isEnabled = false
        //获取验证码
        binding.getCode.setOnClickListener {
            viewModel.sendCode(binding.etPhone.text.toString())
        }
        //点击登录按钮，实现登录功能
        binding.login.setOnClickListener {
            viewModel.login(binding.etPhone.text.toString(),binding.etCode.text.toString())
        }
    }

    override fun initData() {
        //解析验证码返回值
        viewModel.sendCodeSuccess.observe(this){
            if(it.code==200){
                val code = it.data.content.substring(8,14)//截取验证码
                binding.etCode.setText(code)//显示在验证码出
                binding.login.isEnabled = true//登录按钮可用
            }
        }
        viewModel.loginSuccess.observe(this){
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                ToastUtils.showLong(it.message)
                ARouter.getInstance().build("/app/MainActivity").navigation()
                //保存用户信息
                AppDbUtils.getDb().getLoginDao().insert(it.data)
                Log.d("sss", "initData: ${AppDbUtils.getDb().getLoginDao().query("15231282669")?.nikeName}")
            }
        }
    }

}